package handler

import (
	"6-11zk/api/request"
	"6-11zk/api/response"
	"6-11zk/dao"
	"6-11zk/inits"
	"6-11zk/model"
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

func SupplierCreate(c *gin.Context) {
	var data request.SupplierCreate
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	supplier := model.Supplier{
		Model:            gorm.Model{},
		SupplierName:     data.SupplierName,
		SupplierLevel:    data.SupplierLevel,
		Contacts:         data.Contacts,
		ContactsPhone:    data.ContactsPhone,
		ContactsEmail:    data.ContactsEmail,
		ContactsPosition: data.ContactsPosition,
		Address:          data.Address,
		ShowAddress:      data.ShowAddress,
		Notes:            data.Notes,
	}
	err = dao.SupplierCreate(&supplier)
	if err != nil {
		response.ResponseError(c, "供应商添加失败")
		return
	}
	response.ResponseSuccess(c, "供应商添加成功")
}

func SupplierList(c *gin.Context) {
	var data request.SupplierList
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	list, err := dao.SupplierList(data.Page, data.Page, data.SupplierName, data.Contacts, data.Address)
	if err != nil {
		response.ResponseError(c, "查询失败")
		return
	}
	var lists []*model.Supplier
	for _, i2 := range list {
		lists = append(lists, &model.Supplier{
			Model:            gorm.Model{},
			SupplierName:     i2.SupplierName,
			SupplierLevel:    i2.SupplierLevel,
			Contacts:         i2.Contacts,
			ContactsPhone:    i2.ContactsPhone,
			ContactsEmail:    i2.ContactsEmail,
			ContactsPosition: i2.ContactsPosition,
			Address:          i2.Address,
			ShowAddress:      i2.ShowAddress,
			Notes:            i2.Notes,
		})
		marshal, err := json.Marshal(&lists)
		if err != nil {
			response.ResponseError(c, "解析失败")
			return
		}
		inits.Rdb.Set(context.Background(), "supplier:list", marshal, time.Minute*30)
	}
	response.ResponseSuccess(c, lists)

}
